package arpc

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"time"
)

type EncryptionType int

const (
	SHA_256 EncryptionType = 1
)

const (
	AuthOK = iota
	AuthTimestampError
	AuthExpireError
	AuthSignatureError
)

func genSignature(key, cid, id, ts, userdata string) string {
	data := cid + ":" + id + ":" + ts + ":" + userdata

	mac := hmac.New(sha256.New, []byte(key))
	mac.Write([]byte(data))

	encode := mac.Sum(nil)

	return hex.EncodeToString(encode)
}

func GenSignature(key, cid, id, userdata string) (string, string) {
	now := time.Now().Unix()

	ts := strconv.FormatInt(now, 10)

	return ts, genSignature(key, cid, id, ts, userdata)
}

func CheckAuth(timeout int64, signature, key, cid, id, ts, userdata string) int {
	t, err := strconv.ParseInt(ts, 10, 64)
	if err != nil {
		return AuthTimestampError
	}

	now := time.Now().Unix()
	if t < now-timeout || t > now+timeout {
		return AuthExpireError
	}

	sig := genSignature(key, cid, id, ts, userdata)
	if sig != signature {
		return AuthSignatureError
	}

	return AuthOK
}
